/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.rpc.xuelang;

import cn.hutool.json.JSONObject;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.rpc.xuelang.bo.XueLangResponseBo;
import com.comac.ins.isfd.rpc.xuelang.constants.XueLangConstants;
import com.comac.ins.isfd.rpc.xuelang.constants.enums.XueLangResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class XueLangRestTemplateUtils {

    @Autowired
    private RestTemplate xueLangRestTemplate;

    /**
     * 发送 get 请求
     * 默认：客户端接受 json 类型数据
     */
    public XueLangResponseBo get(String url) {
        // 设置默认请求头
        Map<String, String> httpHeaderMap = new HashMap<>();
        httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        return sendRequest(url, HttpMethod.GET, null, httpHeaderMap);
    }

    /**
     * 发送 post 请求
     * 默认：服务器接受 json 类型数据，客户端接受 json 类型数据
     */
    public XueLangResponseBo post(String url, Object requestBody) {
        Map<String, String> httpHeaderMap = new HashMap<>();
        httpHeaderMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        return sendRequest(url, HttpMethod.POST, requestBody, httpHeaderMap);
    }


    /**
     * 发送请求
     *
     * @param method 请求方式
     */
    public XueLangResponseBo sendRequest(String url, HttpMethod method, Object requestBody, Map<String, String> httpHeaderMap) {
        HttpHeaders headers = new HttpHeaders();
        // 设置请求头
        httpHeaderMap.keySet().forEach(key -> {
            headers.add(key, httpHeaderMap.get(key));
        });
        log.info("调用第三方雪浪服务项目接口地址：{} , 入参：{}", url, JsonUtils.toJsonString(requestBody));
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<JSONObject> response = xueLangRestTemplate.exchange(url, method, entity, JSONObject.class);
        if (!response.getStatusCode().is2xxSuccessful()) {
            log.error("调用第三方雪浪服务项目接口失败,response status code is {}", response.getStatusCode());
            throw new BaseException("调用第三方雪浪服务项目接口失败。");
        }
        JSONObject body = response.getBody();
        if (body == null) {
            throw new BaseException("调用第三方雪浪服务项目接口失败，返回体body为空。");
        }
        Integer code = body.getInt(XueLangConstants.CODE);

        if (!XueLangResponseCodeEnum.SUCCESS.getValue().equals(code)) {
            log.error("调用第三方雪浪服务项目接口失败,response error code is {}", code);
            throw new BaseException("调用第三方雪浪服务项目接口失败，返回的code不正确");
        }

        XueLangResponseBo xueLangResponseBo = new XueLangResponseBo();
        String data = body.getStr(XueLangConstants.DATA);
        String msg = body.getStr(XueLangConstants.MSG);
        xueLangResponseBo.setCode(code);
        xueLangResponseBo.setMsg(msg);
        xueLangResponseBo.setData(data);
        log.info("调用第三方雪浪服务项目接口成功，返回参数data：{}",
            data == null ? "" : JsonUtils.toJsonString(data));
        return xueLangResponseBo;
    }


    /**
     * 在 url 后面拼接参数
     *
     * @param url      原请求路径
     * @param paramMap 参数map
     */
    public String getParamUrl(String url, Map<String, String> paramMap) {
        StringBuilder sb = new StringBuilder(url);
        if (paramMap != null && !paramMap.isEmpty()) {
            sb.append("?");
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key).append("=").append(value).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
